﻿using System.Text;

namespace CMB_PAY
{
    public static class CMB_SignUtil
    {
        public static string GetSignContent(Dictionary<string, string> sortedParams)
        {
            //字典排序，并用&进行拼接，例如，b=a，a=b，拼接后变成a=b&b=a
            StringBuilder content = new StringBuilder();
            //利用linq进行字典升序的排序
            var dicSort = from objDic in sortedParams orderby objDic.Key select objDic;
            foreach (KeyValuePair<string, string> kvp in dicSort)
            {
                string key = kvp.Key;
                string value = kvp.Value;
                if (null != key && null != value)
                {
                    content.Append(key + "=" + value + "&");
                }
            }
            if (content.Length != 0)
            {
                content.Remove(content.Length - 1, 1);
            }
            return content.ToString();
        }

        public static string GetSign(Dictionary<string, string> sortedParams)
        {
            //排序拼接参数
            string signContent = GetSignContent(sortedParams);
            Console.WriteLine("待签名原文:");
            Console.WriteLine(signContent);
            //加签
            string sign = CMB_GmUtil.generateSmSign(signContent);
            Console.WriteLine("签名后值:");
            Console.WriteLine(sign);
            return sign;
        }

        public static bool VerifySign(Dictionary<string, string> sortedParams)
        {
            //获取返回的sign
            String returnSign = sortedParams["sign"];
            Console.WriteLine("返回的签名:");
            Console.WriteLine(returnSign);
            //删除返回的sign
            sortedParams.Remove("sign");
            //排序拼接参数
            string signContent = GetSignContent(sortedParams);
            Console.WriteLine("待验签原文:");
            Console.WriteLine(signContent);
            //验签
            bool flag = CMB_GmUtil.verifySmSign(signContent, returnSign);
            Console.WriteLine("验签结果:");
            Console.WriteLine(flag);
            return flag;
        }
    }
}
